package client;

import annotation.Component;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class componentScan {

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<String, Object>();
        String packageName="bean";
        //对于点“.”这个符号在正则表达式中，是代表所有字符的意思，所以要转义一下
        //所以需要两个\\
        String packagePath = packageName.replace("\\.", "/");
        URL url = ClassLoader.getSystemClassLoader().getResource(packagePath);
        //获取绝对路径
        String path = url.getPath();
        //获取绝对路径下的所有文件
        File file = new File(path);
        File[] files = file.listFiles();
        Arrays.stream(files).forEach(f->{

            try {
            System.out.println(f.getName().split("\\.")[0]);
            String className = packageName + "." + f.getName().split("\\.")[0];

                Class<?> aClass = Class.forName(className);
                //判断类上是否是注解
                if(aClass.isAnnotationPresent(Component.class)){

                    Component component = aClass.getAnnotation(Component.class);
                    String id = component.value();

                    Object o = aClass.newInstance();
                    map.put(id,o);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println(map);
    }
}
